package com.example.demo.shIM;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

/**
 * @author jason
 */
@ServerEndpoint(value = "/shIM/{userId}")
@Component
public class ShIMSocketServer {
    private final static Logger logger = LoggerFactory.getLogger(ShIMSocketServer.class);

    private static int onlineCount = 0;
    private static CopyOnWriteArraySet<ShIMSocketServer> webSocketSet = new CopyOnWriteArraySet<ShIMSocketServer>();
    private Session session;
    private String userId = "";

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId) {
        this.session = session;
        webSocketSet.add(this);
        addOnlineCount();
        this.userId = userId;
        try {
            batchSend(userId + ":上线");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        webSocketSet.remove(this);
        subOnlineCount();
    }

    /**
     * 收到客户端消息后调用的方法
     *
     * @param message 客户端发送过来的消息
     */
    @OnMessage
    public void onMessage(String message, Session session) throws IOException {
        batchSend(message);
        //群发消息
    }

    /**
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {

        error.printStackTrace();
    }

    /**
     * 实现服务器主动推送
     */
    public void sendMessage(String message) throws IOException {
        synchronized (this.session) {
            if (this.session.isOpen()) {
                /*使用异步发送消息的方法*/
                this.session.getBasicRemote().sendText(message);
            } else {
                logger.info("链接已经关闭，后台静默执行;");
            }
        }

    }

    /**
     * userId为null群发自定义消息
     */
    public void batchSend(String message) throws IOException {
        for (ShIMSocketServer item : webSocketSet) {
            try {
                //这里可以设定只推送给这个userId的，为null则全部推送
                if (!this.userId.equals(item.userId)) {
                    item.sendMessage(message);
                }
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        ShIMSocketServer.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        ShIMSocketServer.onlineCount--;
    }

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        return super.equals(obj);
    }
}